﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace RfidCompareWin
{
    public class MouseKeyboardSimulator
    {
        // 导入Windows API
        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern bool SetCursorPos(int x, int y);

        [DllImport("user32.dll")]
        private static extern void mouse_event(uint dwFlags, int dx, int dy, uint dwData, int dwExtraInfo);

        // 鼠标事件常量
        private const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
        private const uint MOUSEEVENTF_LEFTUP = 0x0004;
        private const int SW_RESTORE = 9;
        /// <summary>
        /// 激活并前置浏览器窗口
        /// </summary>
        /// <param name="browserType">浏览器类型："edge" 或 "chrome"</param>
        public static void ActivateBrowser(string browserType)
        {
            string processName = browserType.ToLower() switch
            {
                "edge" => "msedge",
                "chrome" => "chrome",
                _ => throw new ArgumentException("不支持的浏览器类型")
            };

            Process[] processes = Process.GetProcessesByName(processName);
            if (processes.Length > 0)
            {
                IntPtr hWnd=IntPtr.Zero;
                // 获取第一个找到的浏览器进程
                for (int i = 0;i<processes.Length;i++)
                {
                    Process browserProcess = processes[i];
                    hWnd = browserProcess.MainWindowHandle;
                    if (hWnd != IntPtr.Zero)
                        break;
                }
               
               

                // 如果窗口最小化，则恢复
                if (IsIconic(hWnd))
                {
                    ShowWindow(hWnd, SW_RESTORE);
                }

                // 设置为前台窗口
                SetForegroundWindow(hWnd);
                Thread.Sleep(500); // 等待窗口激活
            }
            else
            {
                throw new InvalidOperationException($"未找到{browserType}浏览器进程");
            }
        }

        /// <summary>
        /// 模拟鼠标点击指定屏幕坐标
        /// </summary>
        /// <param name="x">屏幕X坐标</param>
        /// <param name="y">屏幕Y坐标</param>
        public static void ClickAt(int x, int y)
        {
            // 移动鼠标到指定位置
            SetCursorPos(x, y);

            // 短暂延迟，确保鼠标移动到位
            Thread.Sleep(50);

            // 模拟鼠标左键按下和释放
            mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
            Thread.Sleep(20); // 模拟真实点击的间隔
            mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
        }

        /// <summary>
        /// 模拟键盘输入字符串
        /// </summary>
        /// <param name="text">要输入的字符串</param>
        public static void TypeText(string text)
        {
            // 确保目标窗口有焦点
            Thread.Sleep(200);

            // 逐个字符输入
            foreach (char c in text)
            {
                // 处理特殊字符
                if (char.IsUpper(c))
                {
                    // 大写字母需要同时按下Shift键
                    SendKeys.SendWait("+{" + c + "}");
                }
                else if (c == ' ')
                {
                    SendKeys.SendWait(" ");
                }
                else if (c == '{')
                {
                    SendKeys.SendWait("{{}");
                }
                else if (c == '}')
                {
                    SendKeys.SendWait("{}}");
                }
                else if (c == '+')
                {
                    SendKeys.SendWait("{+}");
                }
                else if (c == '^')
                {
                    SendKeys.SendWait("{^}");
                }
                else if (c == '%')
                {
                    SendKeys.SendWait("{%}");
                }
                else if (c == '~')
                {
                    SendKeys.SendWait("{~}");
                }
                else
                {
                    // 普通字符直接发送
                    SendKeys.SendWait(c.ToString());
                }

                // 字符之间添加小延迟，更接近真实输入
                Thread.Sleep(30);
            }
        }

        /// <summary>
        /// 在指定坐标点击并输入文本
        /// </summary>
        /// <param name="x">屏幕X坐标</param>
        /// <param name="y">屏幕Y坐标</param>
        /// <param name="text">要输入的文本</param>
        public static void ClickAndType(int x, int y, string text)
        {
           // ActivateBrowser("edge");//这个应该在识别之前完成
            ClickAt(x, y);
            TypeText(text);
        }
    }
}
